package com.jbh.apilibrary.api

import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import com.google.gson.Gson
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl



class MyCookieJar: CookieJar {


    companion object{
        fun saveCookie(cookies:MutableList<Cookie>){
            val sharedPreferences= Api.context?.getSharedPreferences("cookie",MODE_PRIVATE)
            sharedPreferences?.apply {
                edit().putString("map",Gson().toJson(CookieBean("key",cookies))).commit()
            }
        }

        fun readCookie():MutableList<Cookie>?{
            val sharedPreferences= Api.context?.getSharedPreferences("cookie",MODE_PRIVATE)
            val text = sharedPreferences?.getString("map","")
            val cookieBean = Gson().fromJson<CookieBean>(text,CookieBean::class.java)
            if (cookieBean!=null&&cookieBean.cookies.isNotEmpty()){
                return cookieBean.cookies
            }
            return null
        }

        fun clearCookie(){
            val sharedPreferences= Api.context?.getSharedPreferences("cookie",MODE_PRIVATE)
            sharedPreferences?.edit()?.clear()?.commit()
        }

        class CookieBean(var key:String,var cookies:MutableList<Cookie>)
    }


    /**
     * 返回的
     */
    override fun saveFromResponse(url: HttpUrl?, cookies: MutableList<Cookie>?) {
        for (c in cookies!!){
            if (c.name().contains("loginUserName")){
                saveCookie(cookies)
            }
            println("[cookies]->cookies=${Gson().toJson(c)}")
        }
    }

    override fun loadForRequest(url: HttpUrl?): MutableList<Cookie> {
//        val list= mutableListOf<Cookie>()
//        list.add(Cookie.Builder()
//            .name("loginUserName")
//            .value("yxj02")
//            .domain("wanandroid.com")
//            .build())
//        list.add(Cookie.Builder()
//            .name("loginUserPassword")
//            .value("000000")
//            .domain("wanandroid.com")
//            .build())
        println("[cookies]->cookies=${Gson().toJson(readCookie())}")
        if (readCookie() !=null){
            return readCookie()!!
        }
        return ArrayList()
    }
}